const KEY = 'players.simple.list';

function read() {
  try {
    const raw = localStorage.getItem(KEY);
    if (!raw) return [];
    const arr = JSON.parse(raw);
    if (Array.isArray(arr)) return arr;
    return [];
  } catch (e) {
    return [];
  }
}

function write(list) {
  localStorage.setItem(KEY, JSON.stringify(list));
}

export function getPlayers() {
  const list = read();
  if (list.length === 0) {
    const seed = [
      { id: 'p1', name: 'Player A', number: 7 },
      { id: 'p2', name: 'Player B', number: 10 },
      { id: 'p3', name: 'Player C', number: 23 },
    ];
    write(seed);
    return seed;
  }
  return list;
}

export function getPlayerById(id) {
  const list = read();
  return list.find(p => String(p.id) === String(id));
}

export function savePlayer(player) {
  const list = read();
  const idx = list.findIndex(p => String(p.id) === String(player.id));
  const data = { id: String(player.id), name: player.name, number: Number(player.number) };
  if (idx >= 0) {
    list[idx] = data;
  } else {
    list.push(data);
  }
  write(list);
}


